using System.ComponentModel;
using System.Linq;
namespace SB2.Core;

/// <summary>
/// sql 脚本执行
/// </summary>
public class ScriptWithSql : IDynamicFunction, ITransient
{
    protected readonly ISqlSugarClient _dbContext = Furion.App.GetService<ISqlSugarClient>();
    public virtual async Task<object> RunAsync(DynamicFunctionExcDto param)
    {
        if (param.Script == null) throw new Exception("sql无效脚本");
        var sql = param.Script.GetCode();
        var parameters = GetParameters(param.Param.Request);
        try
        {
            Console.WriteLine(parameters.Count);
            var dt = await _dbContext.Ado.GetDataTableAsync(sql, parameters);
            Console.WriteLine("----------");
            return dt.ToDynamic();
        }
        catch (Exception e)
        {
            throw new Exception($"sql脚本内执行失败：{e.Message}");
        }
    }
    /// <summary>
    /// 默认参数
    /// </summary>
    /// <value></value>
    List<SugarParameterDto> DefaultParameters = new List<SugarParameterDto> {
        new SugarParameterDto("now",DateTime.Now,System.Data.DbType.DateTime),
        new SugarParameterDto("CreateUser",-1,System.Data.DbType.Int64),

};
    /// <summary>
    /// 参数解析
    /// </summary>
    /// <param name="parameters"></param>
    /// <returns></returns>
    protected List<SugarParameter> GetParameters(object parameters)
    {
        try
        {
            var stringParm = (parameters != null && parameters.GetType() == typeof(string)) ? parameters + "" : parameters.ToJson() + "";
            var dto = string.IsNullOrEmpty(stringParm) ? new List<SugarParameterDto>()
            : stringParm
            .ToObject<List<SugarParameterDto>>()
            .ToList();
            DefaultParameters.ForEach(m =>
            {
                if (!dto.Any(p => p.Name == m.Name))
                {
                    dto.Add(m);
                }
            });

            dto.ForEach(m =>
            {
                Console.WriteLine(m.GetVaule().GetType() + "===" + m.Name);
            });

            return dto
            .Select(m => new SugarParameter(m.Name, m.GetVaule(), m.Type))
            .ToList();
        }
        catch (Exception e)
        {
            throw new Exception($"参数[{parameters?.ToJson()}]解析失败：{e.Message}");
        }
    }
}
